package cn.spike.basic.controller;

import cn.spike.basic.util.AjaxResult;
import cn.spike.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author:spike
 * @create:2023-02-04 19:19
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 文件上传接口
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult uploadFile(@RequestPart MultipartFile file){
        try {
            //获取到file的原始文件名
            String oName = file.getOriginalFilename();
            //获取到file的拓展名
            String extName = oName.substring(oName.lastIndexOf(".") + 1);
            String upload = FastDfsUtils.upload(file.getBytes(), extName);
            return AjaxResult.me().setObj(upload);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }

    /**
     * 删除接口
     * @return
     * delete http://localhost:8080/fastDfs/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     * 后端接收：@PathV("/{a}/{b}/{c}/{d}") - 麻烦
     * delete http://localhost:8080/fastDfs?path=/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     */
    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam("path")String path){
        try {
            path = path.substring(1);
            String groupName = path.substring(0,path.indexOf("/"));
            String fileName = path.substring(path.indexOf("/") + 1);
            FastDfsUtils.delete(groupName,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

}
